﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace MySqlDemo
{
    public class ExceptionHandlerMiddleWare
    {
        private readonly RequestDelegate _next;

        public ExceptionHandlerMiddleWare(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context, ILogger<ExceptionHandlerMiddleWare> logger)
        {
            try
            {
                await _next(context);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, ex.StackTrace);
                await HandleExceptionAsync(context, ex);
            }
        }

        private static async Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            if (exception == null)
            {
                return;
            }

            await WriteExceptionAsync(context, exception).ConfigureAwait(false);
        }

        private static async Task WriteExceptionAsync(HttpContext context, Exception exception)
        {
            //返回友好的提示
            HttpResponse response = context.Response;

            //状态码
            int StatusCode = 500;
            string message = exception.Message;

            if (exception is UserFriendlyException)
            {
                StatusCode = 400;
                message = exception.Message;
            }
            if (exception is AuthorizationException)
            {
                StatusCode = 401;
                message = "没有权限访问";
            }

            response.ContentType = context.Request.Headers["Accept"];

            var resp = new 
            {
                message = message,
            };
            response.StatusCode = StatusCode;
            response.ContentType = "application/json";
            await response.WriteAsync(JsonConvert.SerializeObject(resp)).ConfigureAwait(false);
        }

    }
}
